package com.lgmshare.component.utils;

import java.util.ArrayList;

/**
 * 拼音转换字母工具类
 * User : Lim
 * Email: lgmshare@gmail.com
 * Datetime : 2015/4/22 17:57
 * To change this template use File | Settings | File Templates.
 */
public final class HanZiToPinyinUtils {

    private HanZiToPinyinUtils() {
    }

    /**
     * 获取汉字字符串的首字母，英文字符不变
     * 例如：阿飞→af
     *
     * @param chines
     * @return
     */
    public static String getPinYinHeadChar(String chines) {
        if (StringUtils.isEmpty(chines)) {
            return "";
        }
        ArrayList<HanZiToPinyin.Token> tokens = HanZiToPinyin.getInstance().get(chines);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanZiToPinyin.Token token : tokens) {
                if (HanZiToPinyin.Token.PINYIN == token.type) {
                    sb.append(token.target.charAt(0));
                } else {
                    sb.append(token.source);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 返回字符串对应拼音，字母返回其大写，特殊符号返回空字符串
     *
     * @param chines
     * @return
     */
    public static String getPinYin(String chines) {
        if (StringUtils.isEmpty(chines)) {
            return "";
        }
        ArrayList<HanZiToPinyin.Token> tokens = HanZiToPinyin.getInstance().get(chines);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanZiToPinyin.Token token : tokens) {
                if (HanZiToPinyin.Token.PINYIN == token.type) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取汉字首字母拼音
     *
     * @param chines
     * @return
     */
    public static String getPinYinFirstLetter(String chines) {
        if (StringUtils.isEmpty(chines)) {
            return "";
        }
        String letter = String.valueOf(chines.charAt(0));
        return getPinYin(letter);
    }
}